package com.dd.shop4j.website.member.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dd.shop4j.common.utils.EncryptUtils;
import com.dd.shop4j.member.model.MemberInfo;
import com.dd.shop4j.website.member.security.UserSecurityInterceptor;
import com.dd.shop4j.website.member.service.MemberService;

@Controller
@RequestMapping("/member")
public class MemberLoginController {
	
	@Resource MemberService memberService;

	@RequestMapping("/test")
	public String test() {
		return "/website/member/test";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/website/member/login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String username, String password, HttpServletRequest request) {
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			request.setAttribute("login_error", "用户名和密码不能为空");
			return "/website/member/login";
		}
		MemberInfo member = memberService.getMemberInfoByUsername(username);
		//如果用户信息不为空，并且密码匹配。那么认为登录成功，将登录信息保存到session中去
		if (member != null 
				&& member.getPassword().equals(EncryptUtils.encrypt(password))) {
			//登录成功后设置最后登录时间和最后登录ip
			member.setLoginTime(new Date());
			member.setLoginIp(request.getRemoteHost());
			//保存登录信息到session中去
			HttpSession session = request.getSession();
			session.setAttribute(UserSecurityInterceptor.loginSessionToken, member);
			session.setAttribute("member", member);
			memberService.logger("会员登录成功");
			return "redirect:/member/main";
		}
		request.setAttribute("login_error", "用户名或密码错误");
		return "/website/member/login";
	}
	
	@RequestMapping("/main")
	public String main() {
		return "/website/member/main";
	}
	
	@RequestMapping("/logout")
	public String logout() {
		memberService.logger("会员注销登录");
		return "/website/member/login";
	}
	
}
